<template>
  <div class="user_info2">
    <x-header :left-options="{showBack: true, backText: ''}" style="">个人资料</x-header>
    <template>

          <!--<div>-->
      <group label-width="9rem" title="" class="group-first">
        <cell title="头像" is-link @click.native="showMenus = true">
          <!--<div>-->
          <div class="avatar">
            <div class="picture">
              <img :src="headerImage" alt="">
            </div>
            <!-- <input type="file" accept="image/*" @change="change" style=" position: absolute;left: 0; top:0;width:100%;height:100%;opacity: 0;"> -->
          </div>
        </cell>

        <cell title="名字" :value="userData.user_login"></cell>
        <cell title="性别" :value="userData.sex"></cell>
        <cell :value="userData.birthday" title="出生年月"></cell>

        <cell primary="content" title="个人承诺" is-link link="/user/info/pledge" :value="userData.promise"></cell>
      </group>

      <group>
        <cell title="手机号" :value="userInfo.mobile"></cell>
        <cell title="邮箱" :value="userInfo.user_email"></cell>
      </group>

      <group>
        <cell :value="userInfo.party_time"  title="入党时间"></cell>
        <cell title="党员类别" :value="userInfo.cate"></cell>
        <cell title="工作单位" :value="userInfo.company"></cell>
        <cell title="所在党支部" :value="userInfo.department"></cell>
        <cell title="党内职务" :value="userInfo.job || jobnull"></cell>
      </group>
    </template>
    <div class="imgPopup" v-transfer-dom>
        <!-- 遮罩层 -->
        <popup class="container" v-show="panel" height="100%">
          <div class="popup">
            <img id="image1" :src="url" alt="Picture">
          </div>
          <div class="operate">
            <button type="button" @click="panel=false">取消</button>
            <button type="button" @click="crop">确定</button>
          </div>
        </popup>
    </div>
    <div v-transfer-dom>
      <actionsheet :menus="menus" theme="android" v-model="showMenus" @on-click-menu-menuSelect="getPictureCapture()"
      @on-click-menu-menuCapture="getPicture()"></actionsheet>
    </div>
  </div>
</template>

<script>
import { XHeader, Actionsheet, TransferDom, Group, Cell, Popup } from "vux";
import { mapGetters } from "vuex";
import Cropper from "cropperjs"; //上传头像插件
import api from "../../api/index.js";
import axios from "axios";

export default {
  directives: {
    TransferDom
  },
  mounted() {
    //初始化这个裁剪框
    var self = this;
    var image = document.getElementById("image1");
    this.cropper = new Cropper(image, {
      aspectRatio: 1,
      viewMode: 1,
      background: false,
      zoomable: false,
      ready: function() {
        self.croppable = true;
      }
    });
  },
  name: "Info",
  components: {
    XHeader,
    Actionsheet,
    Group,
    Cell,
    Popup
  },
  data() {
    return {
      menus: {
        menuSelect: "拍照",
        menuCapture: "从相册选取"
      },
      showMenus: false,

      userData: {},
      baseURL: "",
      base64: "",
      headerImage: require("./img/default-user.png"),
      jobnull: "无",
      picValue: "",
      cropper: "",
      croppable: false,
      panel: false,
      url: ""
    };
  },

  methods: {
    getPicture() {
      navigator.camera.getPicture(
        this.onPictureSuccess,
        this.onPictureFailure,
        {
          quality: 50,
          sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
          destinationType: Camera.DestinationType.FILE_URI,
          saveToPhotoAlbum: true
        }
      );
    },
    onPictureSuccess(imageData) {
      // console.log(imageData)
      // return this.imageSrc = imageData
      this.uploadImage(imageData);
      // return (this.headerImage = imageData);
    },
    onPictureFailure(message) {
      console.log(message);
    },
    getPictureCapture() {
      navigator.camera.getPicture(
        this.onPictureCaptureSuccess,
        this.onPictureFailure,
        {}
      );
    },
    getPictureCapture() {
      navigator.camera.getPicture(
        this.onPictureCaptureSuccess,
        this.onPictureFailure,
        {
          quality: 50,
          sourceType: Camera.PictureSourceType.CAMERA,
          destinationType: Camera.DestinationType.FILE_URI,
          saveToPhotoAlbum: true
        }
      );
    },
    onPictureCaptureSuccess(imageData) {
      // console.log(imageData)
      // return this.imageCaptureSrc = imageData
      this.uploadImage(imageData);
      // return (this.headerImage = imageData);
    },
    uploadImage(image) {
      var self = this;
      var formData = new FormData();

      window.resolveLocalFileSystemURL(
        image,
        function(fileEntry) {
          fileEntry.file(
            function(file) {
              //裁剪图片

              var reader = new FileReader();

              reader.readAsDataURL(file);

              reader.onload = function(e) {
                var src = e.target.result;

                var data;
                var img = new Image();
                img.src = src;

                img.onload = function() {
                  if (src.length <= 100 * 1024) {
                    data = src;
                  } else {
                    data = self.compress(img);
                  }

                  self.panel = true;
                  self.picValue = file;

                  // self.url = file.localURL;
                  self.url = data;

                  //每次替换图片要重新得到新的url
                  if (self.cropper) {
                    self.cropper.replace(self.url);
                  }
                };
              };
              reader.onloadend = function(e) {};
            },
            function(e) {
              // $scope.errorHandler(e)
            }
          );
        },
        function(e) {}
      );
    },
    getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) {
        // basic
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },
    change(e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.panel = true;
      this.picValue = files[0];

      this.url = this.getObjectURL(this.picValue);

      //每次替换图片要重新得到新的url
      if (this.cropper) {
        this.cropper.replace(this.url);
      }
    },
    crop() {
      this.panel = false;
      var croppedCanvas;
      var roundedCanvas;

      if (!this.croppable) {
        return;
      }
      // Crop
      croppedCanvas = this.cropper.getCroppedCanvas();
      //console.log("cropper"+this.cropper)
      // Round
      roundedCanvas = this.getRoundedCanvas(croppedCanvas);

      this.headerImage = roundedCanvas.toDataURL();

      this.postImg();
    },
    getRoundedCanvas(sourceCanvas) {
      var canvas = document.createElement("canvas");
      var context = canvas.getContext("2d");
      var width = sourceCanvas.width;
      var height = sourceCanvas.height;

      canvas.width = width;
      canvas.height = height;

      context.imageSmoothingEnabled = true;
      context.drawImage(sourceCanvas, 0, 0, width, height);
      context.globalCompositeOperation = "destination-in";
      context.beginPath();
      context.arc(
        width / 2,
        height / 2,
        Math.min(width, height) / 2,
        0,
        2 * Math.PI,
        true
      );
      context.fill();

      return canvas;
    },
    dataURItoBlob(dataUrl) {
      var byteString = atob(dataUrl.split(",")[1]);
      var mimeString = dataUrl
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },
    postImg() {
      //这边写图片的上传
      const _this = this;

      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      let userid = window.localStorage.getItem("user");

      let uploadData = new FormData();
      uploadData.append(
        "image",
        this.dataURItoBlob(this.headerImage),
        "image.jpeg"
      );
      uploadData.append("id", userid);

      let ax = axios.create();
      ax.post("/user/index/add", uploadData, config).then(res => {
        if (res.data.code === 1) {
          this.$vux.toast.text("上传成功", "middle");
        } else {
          this.$vux.toast.text(res.data.msg, "middle");
        }
      });
    },
    compress(img) {
      let canvas = document.createElement("canvas");
      // let ctx = canvas.getContext("2d");
      let context = canvas.getContext("2d");
      //瓦片canvas
      // let tCanvas = document.createElement("canvas");
      // let tctx = tCanvas.getContext("2d");
      var originWidth = img.width;
      var originHeight = img.height;
      let initSize = img.src.length;
      // 最大尺寸限制
      var maxWidth = 800,
        maxHeight = 800;
      // 目标尺寸
      var targetWidth = originWidth,
        targetHeight = originHeight;
      // 图片尺寸超过800x800的限制
      if (originWidth > maxWidth || originHeight > maxHeight) {
        if (originWidth / originHeight > maxWidth / maxHeight) {
          // 更宽，按照宽度限定尺寸
          targetWidth = maxWidth;
          targetHeight = Math.round(maxWidth * (originHeight / originWidth));
        } else {
          targetHeight = maxHeight;
          targetWidth = Math.round(maxHeight * (originWidth / originHeight));
        }
      }
      // canvas对图片进行缩放
      canvas.width = targetWidth;
      canvas.height = targetHeight;
      // 清除画布
      context.clearRect(0, 0, targetWidth, targetHeight);
      // 图片压缩
      context.drawImage(img, 0, 0, targetWidth, targetHeight);
      // let width = img.width;
      // let height = img.height;
      // //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      // let ratio;
      // if ((ratio = width * height / 4000000) > 1) {
      //   console.log("大于400万像素");
      //   ratio = Math.sqrt(ratio);
      //   width /= ratio;
      //   height /= ratio;
      // } else {
      //   ratio = 1;
      // }
      // canvas.width = width;
      // canvas.height = height;
      // //        铺底色
      // ctx.fillStyle = "#fff";
      // ctx.fillRect(0, 0, canvas.width, canvas.height);
      // //如果图片像素大于100万则使用瓦片绘制
      // let count;
      // if ((count = width * height / 1000000) > 1) {
      //   console.log("超过100W像素");
      //   count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
      //   //            计算每块瓦片的宽和高
      //   let nw = ~~(width / count);
      //   let nh = ~~(height / count);
      //   tCanvas.width = nw;
      //   tCanvas.height = nh;
      //   for (let i = 0; i < count; i++) {
      //     for (let j = 0; j < count; j++) {
      //       tctx.drawImage(
      //         img,
      //         i * nw * ratio,
      //         j * nh * ratio,
      //         nw * ratio,
      //         nh * ratio,
      //         0,
      //         0,
      //         nw,
      //         nh
      //       );
      //       ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
      //     }
      //   }
      // } else {
      //   ctx.drawImage(img, 0, 0, width, height);
      // }
      //修复ios上传图片的时候 被旋转的问题
      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.4);
      console.log("压缩前：" + initSize);
      console.log("压缩后：" + ndata.length);
      console.log(
        "压缩率：" + ~~(100 * (initSize - ndata.length) / initSize) + "%"
      );
      // tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    }
  },
  computed: {
    ...mapGetters(["userInfo"])
  },
  //触发事件
  created() {
    // let userid = window.localStorage.getItem("user");
    // this.$store.dispatch("getInfo", { id: userid });
  },
  activated() {
    let userid = window.localStorage.getItem("user");
    this.$store.dispatch("getInfo", { id: userid });
  },
  //侦听属性
  watch: {
    userInfo: function(val) {
      this.userData = val;
      if (val.avatar) {
        this.headerImage = val.avatar;
      } else {
        this.headerImage = require("./img/default-user.png");
      }
    }
  }
};
</script>

<style lang="less">
@import "../../common/style/uploadImg.less";
.user_info2 {
  padding: 2.875rem 0 0;
  .weui-cells {
    margin-top: 6/16rem !important;
  }
  .group-first .weui-cells {
    margin-top: 0 !important;
  }
  .weui-cell__ft {
    font-size: 13/16rem;
  }
  .avatar {
    width: 45/16rem;
    height: 45/16rem;
    overflow: hidden;
    position: relative;
    border-radius: 50%;
    border: 1px solid #d5d5d5;
    span {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    .picture {
      width: 100%;
      height: 100%;
      overflow: hidden;
      background-position: center center;
      background-repeat: no-repeat;
      background-size: cover;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.imgPopup {
  .container {
    background: rgba(105, 105, 105, 1);
  }

  #image {
    max-width: 100%;
  }
  .popup {
    width: 100%;
    height: 100%;
  }
  .operate {
    position: fixed;
    bottom: 0;
    background: rgba(0, 0, 0, 0.4);
    width: 100%;
    display: flex;
    text-align: center;
    height: 3rem;
    button {
      flex: 1;
      background: none;
      color: #fff;
      font-size: 1.8rem;
    }
  }
}
</style>


